import React, { Component } from 'react';
import {withRouter} from 'react-router-dom';
import { Form, Input, Button, Checkbox, message, Spin } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

import {userUrl} from '@config/url'
import {AUTHORIZE_SUCCESS} from '@config/code'
import mem from '@utils/memory'
import {storeUser, storeToken} from '@utils/store'
import Request from '@utils/request'
import style from './index.module.css'

class LoginForm extends Component {

  state = {isLoading: false}

  onFinish = async (values) => {
    const data = {
      username: values.username,
      password: values.password,
    }
    
    this.setState({isLoading: true})
    setTimeout(() => this.setState({isLoading: false}), 3000)

    const res = await Request(userUrl.login, data)
    console.log('login res', res)
    if (res.code === 200) {
      // message.success('登录成功')
      console.log("login data", res.data)
      mem.user = res.data.user
      storeUser.set(mem.user)
      mem.token = res.data.token
      storeToken.set(mem.token)
      // console.log('mem', mem)
      const {history, to} = this.props
      history.replace(to)
    } else {
      message.error('登录失败', res.msg)
    }

    this.setState({isLoading: false})
  }

  render() {
    return (
      <Form
        name="login"
        className={style["login-form"]}
        initialValues={{ remember: true }}
        onFinish={this.onFinish}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: 'Please input your Username!' }]}
        >
          <Input 
            prefix={<UserOutlined/>}
            placeholder="Username"
            size="large" />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: 'Please input your Password!' }]}
        >
          <Input.Password
            prefix={<LockOutlined/>}
            placeholder="Password"
            size="large"
          />
        </Form.Item>

        <Form.Item>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox  className={style["login-form-remember"]} >Remember me</Checkbox>
          </Form.Item>
          <a className={style["login-form-forgot"]} href="/user/forgot">
            Forgot password
          </a>
        </Form.Item>

        <Form.Item>
          <Spin tip="Loading ..." spinning={this.state.isLoading}>
            <Button 
              type="primary" 
              htmlType="submit" 
              className={style["login-form-button"]}
              size="large"
            >
              Log in
            </Button>
          </Spin>
          <a className={style["login-form-register"]} href="/user/register">Or register now!</a>
        </Form.Item>
      </Form>
    )
  }
}

export default withRouter(LoginForm)